# -*- coding: utf-8 -*-
########################################################################
#
# (c) 2010-2011 Markus Dittrich
#
# This program is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public
# License Version 3 as published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License Version 3 for more details.
#
# You should have received a copy of the GNU General Public
# License along with this program; if not, write to the Free
# Software Foundation, Inc., 59 Temple Place - Suite 330,
# Boston, MA 02111-1307, USA.
#
#######################################################################

from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import

from functools import partial
from datetime import datetime

from PyQt4.QtCore import (QString, Qt, QVariant, SIGNAL, SLOT, QDir,
                          QRect, QDate, QStringList, QTime)
from PyQt4.QtGui import (QMainWindow, qApp, QColor, QBrush,
                         QTextCharFormat, QTableWidgetItem,
                         QMessageBox)

from caliente.gui.ui_main_window import Ui_MainWindow
from caliente.gui.add_event_dialog import AddEventDialog
import caliente.db.db_driver as db



class MainWindow(QMainWindow, Ui_MainWindow):

    def __init__(self, filename = None, parent = None):
        """ Initialize the main window """

        QMainWindow.__init__(self, parent)
        self.setupUi(self)

        self.initialize_database()
        
        self._initialize_gui()
        self._connect_slots()

        self.load_events_from_database()



    def _connect_slots(self):
        """ Connects all slots for main gui. """
        
        self.connect(self.calendarWidget, SIGNAL("selectionChanged()"),
                     self.update_event_widget)

        self.connect(self.todayButton, SIGNAL("pressed()"),
                     partial(set_to_current_date, self.calendarWidget))
        
        self.connect(self.actionQuit, SIGNAL("triggered()"),
                qApp, SLOT("quit()"))
       
        self.connect(self.actionAbout_Caliente, SIGNAL("triggered()"),
                self.show_about_caliente)
                
        self.connect(self.actionAbout_Qt4, SIGNAL("triggered()"),
                self.show_about_qt4)

        self.connect(self.addEventButton, SIGNAL("pressed()"),
                self.open_add_event_dialog)



    def _initialize_gui(self):
        """ Initialize the main gui """

        self.highlight_all_events()
        self.update_event_widget() #self._db, self.calendarWidget, self.eventWidget)
        


    def initialize_database(self):
        """ Initializes the Sqlite3 database storing the calendar
        data.

        """

        homeDir = QDir.homePath()
        self._db = db.CalendarStorage(homeDir) 



    def load_events_from_database(self):
        """ Loads all events stored in the database and adds
        them to the calendar.

        """
        
        print("printint content:")
        foo = self._db.get_all_events()
        print(foo)



    def show_about_caliente(self):
        """ Show the about Caliente dialog. """

        QMessageBox.about(self, "caliente", 
                "caliente is a simple calendar application.\n\n"
                "(C) 2010-2011 Markus Dittrich")



    def show_about_qt4(self):
        """ Show the about Qt dialog. """

        QMessageBox.aboutQt(self)



    def highlight_all_events(self):
        """ Highlights all events in the calendar widget """

        allEvents = self._db.get_all_events()
        [self.highlight_date(dateString_to_date(event["date"])) \
                             for event in allEvents]



    def highlight_date(self, date):
        """ Hightlights the calendar box of the given date. """

        foreColor = QColor(0, 0, 0)
        backColor = QColor(0, 255, 0)
        foreBrush = QBrush(foreColor)
        backBrush = QBrush(backColor)

        textStyle = QTextCharFormat()       
        textStyle.setForeground(foreBrush)
        textStyle.setBackground(backBrush)

        self.calendarWidget.setDateTextFormat(date, textStyle)



    def open_add_event_dialog(self):
        """ This method opens a dialog for adding 
        a new event. If a new event was returned it is saved
        in the database.

        """

        newEvent = {}
        addDialog = AddEventDialog(self.calendarWidget.selectedDate(),
                        newEvent, self)
        addDialog.exec_()

        if newEvent:
            self._db.add_event(newEvent["date"].toPyDate(), 
                               newEvent["time"], 
                               newEvent["duration"], 
                               newEvent["title"], 
                               newEvent["description"])

            self.highlight_date(newEvent["date"])



    def update_event_widget(self):
        """ updates the event widget according to the
        date selected in the calendar widget.

        """

        self.eventWidget.update(self.calendarWidget.selectedDate(),
                                self._db)



def set_to_current_date(calendar):
    """ Sets the calendar widget to the current date. """

    todaysDate = QDate.currentDate()
    calendar.setSelectedDate(todaysDate)



def dateString_to_date(dateString):
    """ Converts a unicode data string (from Sqlite) to
    a QDate object.

    """
    
    return datetime.strptime(dateString,"%Y-%m-%d")


